﻿#region 命名空间

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.IO;
using WinnerCMS.Common;
using WinnerCMS.Data;
using WinnerCMS.Model;

#endregion

namespace WinnerCMS.BLL
{
    /// <summary>
    /// 图片列表
    /// </summary>
    public class PhotoListManage
    {
        private static readonly PhotoListDal MyDAL = new PhotoListDal();

        /// <summary>
        /// 添加图片列表
        /// </summary>
        /// <param name="model"></param>
        public void Add(PhotoList model)
        {
            if (model.Title == null)
            {
                model.Title = string.Empty;
            }
            model.CreateTime = DateTime.Now;
            model.UpdateTime = DateTime.Now;
            MyDAL.Add(model);
        }

        /// <summary>
        /// 修改图片列表
        /// </summary>
        /// <param name="model"></param>
        public void Edit(PhotoList model)
        {
            if (model.Title == null)
            {
                model.Title = string.Empty;
            }
            model.UpdateTime = DateTime.Now;
            MyDAL.Edit(model);
        }

        /// <summary>
        /// 删除图片
        /// </summary>
        /// <param name="id"></param>
        public Result Delete(int id)
        {
            Result res = new Result();
            try
            {
                var info = MyDAL.GetInfo(id);
                if (info == null)
                    return res;
                try
                {
                    File.Delete(HttpServer.MapPath(info.PicUrl));
                }
                catch
                {
                }
                try
                {
                    File.Delete(HttpServer.MapPath(info.ThumbUrl));
                }
                catch
                {
                }
                MyDAL.Delete(id);
            }
            catch (Exception ex)
            {
                res.Errors = ex.Message;
            }
            return res;
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public PhotoList GetInfo(int id)
        {
            return MyDAL.GetInfo(id);
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        /// <param name="contentId"></param>
        /// <returns></returns>
        public IList<PhotoList> GetList(int contentId)
        {
            return MyDAL.GetList(contentId, null);
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        /// <param name="contentId"></param>
        /// <param name="tempFlag"></param>
        /// <returns></returns>
        public IList<PhotoList> GetList(int contentId, string tempFlag)
        {
            return MyDAL.GetList(contentId, tempFlag);
        }

        /// <summary>
        /// 添加内容完成后，设置一下ID的归属
        /// </summary>
        /// <param name="contentId"></param>
        /// <param name="tempFlag"></param>
        public void FinishAction(int contentId, string tempFlag)
        {
            MyDAL.FinishAction(contentId, tempFlag);
        }

        /// <summary>
        /// 更新标题
        /// </summary>
        /// <param name="id"></param>
        /// <param name="title"></param>
        /// <returns></returns>
        public Result UpdateTitle(int id, string title)
        {
            Result res = new Result();
            try
            {
                var info = GetInfo(id);
                if (info == null)
                {
                    return res;
                }
                info.Title = title;

                Edit(info);
            }
            catch (Exception ex)
            {
                res.Errors = ex.Message;
            }
            return res;
        }

        /// <summary>
        /// 更新排序ID
        /// </summary>
        /// <param name="ids">新排序id</param>
        /// <param name="contentId">内容编码</param>
        /// <param name="tempFlag">临时标记</param>
        public Result MoveOrderId(int[] ids, int contentId, string tempFlag)
        {
            Result res = new Result();
            try
            {
                var list = MyDAL.GetList(contentId, tempFlag);
                for (int i = 0; i < ids.Length; i++)
                {
                    var info = list.First(x => x.Id == ids[i]);
                    info.OrderId = i + 1;

                    Edit(info);
                }
            }
            catch (Exception ex)
            {
                res.Errors = ex.Message;
            }
            return res;
        }

        #region 上传图片

        private static readonly object Lockobj = new object();

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public PhotoList Upload(HttpContext context)
        {
            HttpPostedFile fileUpload = context.Request.Files[0];

            const string uploadDir = "~/UpLoadFolder/"; //图片保存的文件夹
            //图片保存的文件夹路径
            string path = context.Server.MapPath(uploadDir);
            //每天上传的图片一个文件夹
            string folder = DateTime.Now.ToString("yyyyMM");
            //如果文件夹不存在，则创建
            if (!Directory.Exists(path + folder))
            {
                Directory.CreateDirectory(path + folder);
            }
            //上传图片的扩展名
            string fileExtension = fileUpload.FileName.Substring(fileUpload.FileName.LastIndexOf('.'));


            //保存图片的文件名
            string saveName = Guid.NewGuid() + fileExtension;

            //保存图片
            string filePath = path + folder + "/" + saveName;
            fileUpload.SaveAs(filePath);


            FileInfo fi = new FileInfo(filePath);

            string strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff"); //取得时间字符串
            Random ran = new Random();
            string strRan = Convert.ToString(ran.Next(100, 999)); //生成三位随机数
            saveName = strDateTime + strRan + fileExtension;

            string newFilePath = path + folder + "/" + saveName;

            string str = null;
            new Thumbnails(filePath).ReducedImage(240, 180, newFilePath, ref str);

            lock (Lockobj)
            {
                PhotoList model = new PhotoList
                {
                    Title = "",
                    ThumbUrl = uploadDir.Replace("~/", "/") + folder + "/" + saveName,
                    PicUrl = uploadDir.Replace("~/", "/") + folder + "/" + fi.Name,
                    ContentId = int.Parse(context.Request["ContentId"]),
                    TempFlag = context.Request["TempFlag"]
                };
                Add(model);


                return model;
            }
        }

        #endregion
    }
}